package org.xjc.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.xjc.exception.CustomException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author XJC
 */
public class SecretUtil {

    public static void main(String[] args) throws Exception {

        System.out.println(encryptByRsa("加密明文加密明文加密明文加密明文加密明文密明文明文明文明文明文明文明文明文明文"));
        String s="加密明文加密明文加密明文加密明文加密明文密明文明文明文明文明文明文明文明文明文";
        System.out.println(s.length());


    }

    public static String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGXsxHtxVl/rcvs4ezSOlfAOswLv1vlx6TQxyR3DOaQ2Fi0C4UvtdVX3mqjzhtjqaWIFlgq5C4BrjArFzCA0HR+FOFDxsnKSKimv3k2gaYCWgbOAQLShmfe5SfYEbziUOyxyM6CAJvDujLAAWzfyUo1XTQUFFgP5tvD6CIwIZ4OwIDAQAB";
    public static String privatekey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIZezEe3FWX+ty+zh7NI6V8A6zAu/W+XHpNDHJHcM5pDYWLQLhS+11VfeaqPOG2OppYgWWCrkLgGuMCsXMIDQdH4U4UPGycpIqKa/eTaBpgJaBs4BAtKGZ97lJ9gRvOJQ7LHIzoIAm8O6MsABbN/JSjVdNBQUWA/m28PoIjAhng7AgMBAAECgYBxdZZ0b8mnx/6STrukzUoRKEtu8h6ZnTb6Dc8P8qm39nFC6JogdkyJEAdB15FEIRHU7hfKItQeL77NIj1orStjkL5b4jFXPl7VQ6EIFRyliVijQWU8GenzO+qvFJsS2DsXv6lvHG5DpNIuBcv1bNxcwedYTgxQKyNEikiul0eaoQJBAMWNdjfwThM/RgkQGD/6niYe39NdOXFO3nvXJ5wdw0M2hz28SivuPk6lCy2c29GlDsYfeAkYvWUVgbyLixu5qKMCQQCuH/DEqEFeZcOlooGCjU9g5L/++gJEiLTHA9qtB5PnprYAi/9w6cTDYiqvb6o8eeLVBB5X8kf7ENwsSB+zjnOJAkB1kDbPGVHNQHVURWC5ClL9SphWt37MwGvEdQjcbhXatOOMyLW3KQOpV6ysS1HBlCGTo/ySJUfolQDtDHoPWNBTAkA+CoVoHKdF8i52uuM4WA87b+X0/LGIJ8l5y6bD1hpeBKl+omM+oRyJnVWmMrxOVgN7cL87CMma7FP2tzAMcyo5AkAWB0aEWgXl/YKCkpnv9hM2E39BDqkKEV206uhcMsX05aVlYrOSHFaaktHjdyxoKW8uES1o9DJ/JxyWriWqM715";

    public SecretUtil() {
    }

    public static String encrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            throw new CustomException("密钥不能为空");
        } else if (sKey.length() != 16) {
            throw new CustomException("密钥长度只能16位");
        } else {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(1, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            return (new Base64()).encodeToString(encrypted);
        }
    }

    public static String decrypt(String sSrc, String sKey) throws Exception {
        if (sKey == null) {
            throw new CustomException("密钥不能为空");
        } else if (sKey.length() != 16) {
            throw new CustomException("密钥长度只能16位");
        } else {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(2, skeySpec);
            byte[] encrypted1 = (new Base64()).decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        }
    }

    public static String encryptByRsa(String content) throws Exception {
        PublicKey publicKey = getPublicKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(1, publicKey);
        byte[] output = cipher.doFinal(content.getBytes());
        return Base64.encodeBase64String(output).replaceAll("\\r", "").replaceAll("\\n", "");
    }

    public static byte[] ByteByRsa(byte[] content) throws Exception {
        PrivateKey publicKey = getPrivateKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(1, publicKey);
        return cipher.doFinal(content);
    }

    public static PublicKey getPublicKey() throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publickey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(keySpec);
    }

    public static PrivateKey getPrivateKey() throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privatekey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(keySpec);
    }

    public static byte[] decrypt(byte[] content) throws Exception {
        PrivateKey privateKey = getPrivateKey();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(2, privateKey);
        return cipher.doFinal(content);
    }

    public static String decryptByRsa(String content) throws Exception {
        PrivateKey privateKey = getPrivateKey();
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(2, privateKey);
        byte[] input = Base64.decodeBase64(content);
        byte[] result = cipher.doFinal(input);
        String str = new String(result);
        return str;
    }
}